/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.sys.service;


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.jeeplus.common.utils.IdGen;
import com.jeeplus.modules.account.mapper.AccountMapper;
import com.jeeplus.modules.address.entity.Address;
import com.jeeplus.modules.address.mapper.AddressMapper;
import com.jeeplus.modules.dynamicrecord.mapper.DynamicRecordMapper;
import com.jeeplus.modules.goods.entity.Goods;
import com.jeeplus.modules.goods.mapper.GoodsMapper;
import com.jeeplus.modules.goods.service.GoodsService;
import com.jeeplus.modules.grouporders.entity.GroupOrders;
import com.jeeplus.modules.grouporders.mapper.GroupOrdersMapper;
import com.jeeplus.modules.grouprecord.entity.GroupRecord;
import com.jeeplus.modules.grouprecord.mapper.GroupRecordMapper;
import com.jeeplus.modules.groupreturn.entity.GroupReturn;
import com.jeeplus.modules.groupreturn.mapper.GroupReturnMapper;
import com.jeeplus.modules.orderbalance.entity.OrderBalance;
import com.jeeplus.modules.orderbalance.mapper.OrderBalanceMapper;
import com.jeeplus.modules.orders.entity.Orders;
import com.jeeplus.modules.orders.mapper.OrdersMapper;
import com.jeeplus.modules.orders.service.OrdersService;
import com.jeeplus.modules.partitioninfo.entity.PartitionInfo;
import com.jeeplus.modules.partitioninfo.mapper.PartitionInfoMapper;
import com.jeeplus.modules.positionassets.entity.PositionAssets;
import com.jeeplus.modules.positionassets.mapper.PositionAssetsMapper;
import com.jeeplus.modules.positionassets.service.PositionAssetsService;
import com.jeeplus.modules.purchaseorder.entity.PurchaseOrder;
import com.jeeplus.modules.purchaseorder.service.PurchaseOrderService;
import com.jeeplus.modules.recharge.entity.Recharge;
import com.jeeplus.modules.recharge.mapper.RechargeMapper;
import com.jeeplus.modules.record.entity.Record;
import com.jeeplus.modules.rewardparameters.entity.RewardParameters;
import com.jeeplus.modules.saleorder.entity.SaleOrder;
import com.jeeplus.modules.saleorder.service.SaleOrderService;
import com.jeeplus.modules.sessions.entity.Sessions;
import com.jeeplus.modules.sessions.mapper.SessionsMapper;
import com.jeeplus.modules.subgoods.entity.SubGoods;
import com.jeeplus.modules.subgoods.service.SubGoodsService;
import com.jeeplus.modules.subrecord.entity.SubRecord;
import com.jeeplus.modules.subrecord.mapper.SubRecordMapper;
import com.jeeplus.modules.teamrecord.entity.TeamRecord;
import com.jeeplus.modules.teamrecord.mapper.TeamRecordMapper;
import com.jeeplus.modules.teamservice.entity.TeamService;
import com.jeeplus.modules.teamservice.mapper.TeamServiceMapper;
import com.jeeplus.modules.teamservice.service.TeamServiceService;
import com.jeeplus.modules.tixian.entity.Tixian;
import com.jeeplus.modules.tixian.mapper.TixianMapper;
import com.jeeplus.modules.tixian.service.TixianService;
import com.jeeplus.modules.traderecord.entity.TradeRecord;
import com.jeeplus.modules.traderecord.mapper.TradeRecordMapper;
import com.jeeplus.modules.traderecord.service.TradeRecordService;
import com.jeeplus.modules.tradingline.entity.TradingLine;
import com.jeeplus.modules.tradingline.service.TradingLineService;
import com.jeeplus.modules.yuyue.entity.Yuyue;
import com.jeeplus.modules.yuyue.mapper.YuyueMapper;
import com.jeeplus.modules.yuyue.service.YuyueService;
import org.apache.shiro.session.Session;
import org.apache.xmlbeans.impl.jam.mutable.MMember;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.AttributeAccessorSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.CacheUtils;
import com.jeeplus.common.utils.Encodes;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.security.Digests;
import com.jeeplus.core.security.shiro.session.SessionDAO;
import com.jeeplus.core.service.BaseService;
import com.jeeplus.core.service.ServiceException;
import com.jeeplus.modules.account.entity.Account;
import com.jeeplus.modules.account.service.AccountService;
import com.jeeplus.modules.dynamicrecord.entity.DynamicRecord;
import com.jeeplus.modules.dynamicrecord.service.DynamicRecordService;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.service.MemberService;
import com.jeeplus.modules.sys.entity.DataRule;
import com.jeeplus.modules.sys.entity.Menu;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.Role;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.mapper.MenuMapper;
import com.jeeplus.modules.sys.mapper.RoleMapper;
import com.jeeplus.modules.sys.mapper.UserMapper;
import com.jeeplus.modules.sys.utils.LogUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 系统管理，安全相关实体的管理类,包括用户、角色、菜单.
 * @author jeeplus
 * @version 2016-12-05
 */
@Service
@Transactional(readOnly = true)
public class SystemService extends BaseService implements InitializingBean {
	
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	public static final int SALT_SIZE = 8;
	
	@Autowired
	private DataRuleService dataRuleService;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private MenuMapper menuMapper;
	@Autowired
	private SessionDAO sessionDao;
	@Autowired
	private MemberService memberService;
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private DynamicRecordService dynamicRecordService;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private OrderBalanceMapper orderBalanceMapper;
	@Autowired
	private YuyueMapper yuyueMapper;
	@Autowired
	private TeamServiceService teamServiceService;
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private PartitionInfoMapper partitionInfoMapper;
	@Autowired
	private GroupRecordMapper groupRecordMapper;
	@Autowired
	private GroupOrdersMapper groupOrdersMapper;
	@Autowired
	private GroupReturnMapper groupReturnMapper;
	@Autowired
	private DynamicRecordMapper dynamicRecordMapper;
	@Autowired
	private PurchaseOrderService purchaseOrderService;
	@Autowired
	private SaleOrderService saleOrderService;
	@Autowired
	private SubGoodsService subGoodsService;
	@Autowired
	private TradeRecordService tradeRecordService;
	@Autowired
	private TradingLineService tradingLineService;
	@Autowired
	private SubRecordMapper subRecordMapper;
	@Autowired
	private TeamServiceMapper teamServiceMapper;
	@Autowired
	private TeamRecordMapper teamRecordMapper;
	@Autowired
	private TradeRecordMapper tradeRecordMapper;
	@Autowired
	private PositionAssetsMapper positionAssetsMapper;
	@Autowired
	private TixianMapper tixianMapper;
	@Autowired
	private RechargeMapper rechargeMapper;



	public SessionDAO getSessionDao() {
		return sessionDao;
	}


	//-- User Service --//
	
	/**
	 * 获取用户
	 * @param id
	 * @return
	 */
	public User getUser(String id) {
		return UserUtils.get(id);
	}

	/**
	 * 根据登录名获取用户
	 * @param loginName
	 * @return
	 */
	public User getUserByLoginName(String loginName) {
		return UserUtils.getByLoginName(loginName);
	}
	
	public Page<User> findUser(Page<User> page, User user) {
		dataRuleFilter(user);
		// 设置分页参数
		user.setPage(page);
		// 执行分页查询
		page.setList(userMapper.findList(user));
		return page;
	}
	
	/**
	 * 无分页查询人员列表
	 * @param user
	 * @return
	 */
	public List<User> findUser(User user){
		dataRuleFilter(user);
		List<User> list = userMapper.findList(user);
		return list;
	}

	/**
	 * 通过部门ID获取用户列表，仅返回用户id和name（树查询用户时用）
	 * @param officeId
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<User> findUserByOfficeId(String officeId) {
		List<User> list = (List<User>)CacheUtils.get(UserUtils.USER_CACHE, UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_ + officeId);
		if (list == null){
			User user = new User();
			user.setOffice(new Office(officeId));
			list = userMapper.findUserByOfficeId(user);
			CacheUtils.put(UserUtils.USER_CACHE, UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_ + officeId, list);
		}
		return list;
	}
	
	@Transactional(readOnly = false)
	public void saveUser(User user) {
		if (StringUtils.isBlank(user.getId())){
			user.preInsert();
			userMapper.insert(user);
		}else{
			// 清除原用户机构用户缓存
			User oldUser = userMapper.get(user.getId());
			if (oldUser.getOffice() != null && oldUser.getOffice().getId() != null){
				CacheUtils.remove(UserUtils.USER_CACHE, UserUtils.USER_CACHE_LIST_BY_OFFICE_ID_ + oldUser.getOffice().getId());
			}
			// 更新用户数据
			user.preUpdate();
			userMapper.update(user);
		}
		if (StringUtils.isNotBlank(user.getId())){
			// 更新用户与角色关联
			userMapper.deleteUserRole(user);
			if (user.getRoleList() != null && user.getRoleList().size() > 0){
				userMapper.insertUserRole(user);
			}else{
				throw new ServiceException(user.getLoginName() + "没有设置角色！");
			}
			// 清除用户缓存
			UserUtils.clearCache(user);
//			// 清除权限缓存
//			systemRealm.clearAllCachedAuthorizationInfo();
		}
	}
	
	@Transactional(readOnly = false)
	public void updateUserInfo(User user) {
		user.preUpdate();
		userMapper.updateUserInfo(user);
		// 清除用户缓存
		UserUtils.clearCache(user);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}
	
	@Transactional(readOnly = false)
	public void deleteUser(User user) {
		userMapper.deleteUserRole(user);
		userMapper.delete(user);
		// 清除用户缓存
		UserUtils.clearCache(user);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}
	
	@Transactional(readOnly = false)
	public void updatePasswordById(String id, String loginName, String newPassword) {
		User user = new User(id);
		user.setPassword(entryptPassword(newPassword));
		userMapper.updatePasswordById(user);
		// 清除用户缓存
		user.setLoginName(loginName);
		UserUtils.clearCache(user);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}
	
	@Transactional(readOnly = false)
	public void updateUserLoginInfo(User user) {
		// 保存上次登录信息
		user.setOldLoginIp(user.getLoginIp());
		user.setOldLoginDate(user.getLoginDate());
		// 更新本次登录信息
		user.setLoginIp(UserUtils.getSession().getHost());
		user.setLoginDate(new Date());
		userMapper.updateLoginInfo(user);
	}
	
	/**
	 * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
	 */
	public static String entryptPassword(String plainPassword) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		return Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword);
	}
	
	/**
	 * 验证密码
	 * @param plainPassword 明文密码
	 * @param password 密文密码
	 * @return 验证成功返回true
	 */
	public static boolean validatePassword(String plainPassword, String password) {
		byte[] salt = Encodes.decodeHex(password.substring(0,16));
		byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
		return password.equals(Encodes.encodeHex(salt)+Encodes.encodeHex(hashPassword));
	}
	
	/**
	 * 获得活动会话
	 * @return
	 */
	public Collection<Session> getActiveSessions(){
		return sessionDao.getActiveSessions(false);
	}
	
	//-- Role Service --//
	
	public Role getRole(String id) {
		return roleMapper.get(id);
	}

	public Role getRoleByName(String name) {
		Role r = new Role();
		r.setName(name);
		return roleMapper.getByName(r);
	}
	
	public Role getRoleByEnname(String enname) {
		Role r = new Role();
		r.setEnname(enname);
		return roleMapper.getByEnname(r);
	}
	
	public List<Role> findRole(Role role){
		return roleMapper.findList(role);
	}
	
	public List<Role> findAllRole(){
		return UserUtils.getRoleList();
	}
	
	@Transactional(readOnly = false)
	public void saveRole(Role role) {
		if (StringUtils.isBlank(role.getId())){
			role.preInsert();
			roleMapper.insert(role);
		}else{
			role.preUpdate();
			roleMapper.update(role);
		}
		// 更新角色与菜单关联
		roleMapper.deleteRoleMenu(role);
		if (role.getMenuList().size() > 0){
			roleMapper.insertRoleMenu(role);
		}
		
		// 更新角色与数据权限关联
		roleMapper.deleteRoleDataRule(role);
		if (role.getDataRuleList().size() > 0){
			roleMapper.insertRoleDataRule(role);
		}
		// 清除用户角色缓存
		UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}

	@Transactional(readOnly = false)
	public void deleteRole(Role role) {
		roleMapper.deleteRoleMenu(role);
		roleMapper.deleteRoleDataRule(role);
		roleMapper.delete(role);
		// 清除用户角色缓存
		UserUtils.removeCache(UserUtils.CACHE_ROLE_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
	}
	
	@Transactional(readOnly = false)
	public Boolean outUserInRole(Role role, User user) {
		List<Role> roles = user.getRoleList();
		for (Role e : roles){
			if (e.getId().equals(role.getId())){
				roles.remove(e);
				saveUser(user);
				return true;
			}
		}
		return false;
	}
	
	@Transactional(readOnly = false)
	public User assignUserToRole(Role role, User user) {
		if (user == null){
			return null;
		}
		List<String> roleIds = user.getRoleIdList();
		if (roleIds.contains(role.getId())) {
			return null;
		}
		user.getRoleList().add(role);
		saveUser(user);
		return user;
	}

	//-- Menu Service --//
	
	public Menu getMenu(String id) {
		return menuMapper.get(id);
	}

	public List<Menu> findAllMenu(){
		return UserUtils.getMenuList();
	}
	
	public List<Menu> getChildren(String parentId){
		return menuMapper.getChildren(parentId);
	}
	
	@Transactional(readOnly = false)
	public void saveMenu(Menu menu) {
		
		// 获取父节点实体
		menu.setParent(this.getMenu(menu.getParent().getId()));
		
		// 获取修改前的parentIds，用于更新子节点的parentIds
		String oldParentIds = menu.getParentIds(); 
		
		// 设置新的父节点串
		menu.setParentIds(menu.getParent().getParentIds()+menu.getParent().getId()+",");

		// 保存或更新实体
		if (StringUtils.isBlank(menu.getId())){
			menu.preInsert();
			menuMapper.insert(menu);
		}else{
			menu.preUpdate();
			menuMapper.update(menu);
		}
		
		// 更新子节点 parentIds
		Menu m = new Menu();
		m.setParentIds("%,"+menu.getId()+",%");
		List<Menu> list = menuMapper.findByParentIdsLike(m);
		for (Menu e : list){
			e.setParentIds(e.getParentIds().replace(oldParentIds, menu.getParentIds()));
			menuMapper.updateParentIds(e);
		}
		// 清除用户菜单缓存
		UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
		// 清除日志相关缓存
		CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
	}

	@Transactional(readOnly = false)
	public void updateMenuSort(Menu menu) {
		menuMapper.updateSort(menu);
		// 清除用户菜单缓存
		UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
//		// 清除权限缓存
//		systemRealm.clearAllCachedAuthorizationInfo();
		// 清除日志相关缓存
		CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
	}

	@Transactional(readOnly = false)
	public void deleteMenu(Menu menu) {

		// 解除菜单角色关联
		List<Map<String, Object>> mrlist =  menuMapper.execSelectSql(
				"SELECT distinct a.menu_id as id FROM sys_role_menu a left join sys_menu menu on a.menu_id = menu.id WHERE a.menu_id ='"
						+ menu.getId() + "' OR menu.parent_ids LIKE  '%," + menu.getId() + ",%'");
		for (Map<String, Object> mr : mrlist) {
			menuMapper.deleteMenuRole(mr.get("id").toString());
		}

		// 删除菜单关联的数据权限数据，以及解除角色数据权限关联
		List<Map<String, Object>> mdlist = menuMapper.execSelectSql(
				"SELECT distinct a.id as id FROM sys_datarule a left join sys_menu menu on a.menu_id = menu.id WHERE a.menu_id ='"
						+ menu.getId() + "' OR menu.parent_ids LIKE  '%," + menu.getId() + ",%'");
		for (Map<String, Object> md : mdlist) {
			DataRule dataRule = new DataRule(md.get("id").toString());
			dataRuleService.delete(dataRule);
		}

		menuMapper.delete(menu);
		// 清除用户菜单缓存
		UserUtils.removeCache(UserUtils.CACHE_MENU_LIST);
		// // 清除权限缓存
		// systemRealm.clearAllCachedAuthorizationInfo();
		// 清除日志相关缓存
		CacheUtils.remove(LogUtils.CACHE_MENU_NAME_PATH_MAP);
	}
	
	/**
	 * 获取产品信息
	 */
	public static boolean printKeyLoadMessage(){
		StringBuilder sb = new StringBuilder();
		sb.append("...．．∵ ∴★．∴∵∴ ╭ ╯╭ ╯╭ ╯╭ ╯∴∵∴∵∴ \r\n ");
		sb.append("．☆．∵∴∵．∴∵∴▍▍ ▍▍ ▍▍ ▍▍☆ ★∵∴ \r\n ");
		sb.append("▍．∴∵∴∵．∴▅███████████☆ ★∵ \r\n ");
		sb.append("◥█▅▅▅▅███▅█▅█▅█▅█▅█▅███◤          欢迎使用 "+Global.getConfig("productName")+Global.getConfig("version")+"\r\n ");
		sb.append("． ◥███████████████████◤                    \r\n ");
		sb.append(".．.．◥████████████████■◤\r\n ");
		System.out.println(sb.toString());
		return true;
	}
	
	public void afterPropertiesSet() throws Exception {
	}


	/**
	 * DayTask
	 */
	@Transactional(readOnly = false)
	public void daycal(){
		makeZero();
	}

	/**
	 * todayDynamic  todayTeam todayProfit 今日的收益明细 全部清零
	 */
	@Transactional(readOnly = false)
	public void makeZero(){
		BigDecimal todayDynamic = BigDecimal.valueOf(0);
		BigDecimal todayTeam = BigDecimal.valueOf(0);
		BigDecimal todayProfit = BigDecimal.valueOf(0);
		List<Account> accountList = accountMapper.findAllList(new Account());
		for (Account account : accountList) {
			account.setTodayDynamic(todayDynamic.doubleValue());
			account.setTodayTeam(todayTeam.doubleValue());
			account.setTodayProfit(todayProfit.doubleValue());
			accountMapper.update(account);
		}
	}


	/**
	 * OrderTask
	 */
	@Transactional(readOnly = false)
	public void ordercal(){
		deleteOrder();
	}

	/**
	 * 15分钟的待付款订单删除
	 */
	@Transactional(readOnly = false)
	public void deleteOrder(){
		try {
			Orders orders = new Orders();
			orders.setOrdersStatus("1");
			List<Orders> list = ordersMapper.findList(orders);
			if (list.size()>0){
				for (Orders orders1 : list) {
					Date orderDate = orders1.getCreateDate();
					Long now = System.currentTimeMillis();
					Long orderTime = orderDate.getTime();
					//30分钟后订单取消
					if ((now-orderTime)/(1000*60) >= 30){
						//更改出售订单   1等待付款 修改  0上架中
						Goods goods = goodsMapper.get(orders1.getGoods().getId());
						//商品改为出售中
						goods.setGoodsStatus("1");
						goods.preUpdate();
						goodsMapper.update(goods);
						if (goods.getOrders() != null){
							Orders entity = ordersMapper.get(goods.getOrders().getId());
							if (entity != null){
								entity.setOrdersStatus("0");
								ordersMapper.update(entity);
							}
						}else {
							//删除购买订单
							orders1.setDelFlag("1");
							ordersMapper.update(orders1);
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}


	/**
	 * 每天00:30动态收益到达5000的用户，扣除一个出售中的订单  500   多的补到余额
	 */
	@Transactional(readOnly = false)
	public void dynamicIncome() {
		//查询所有账户
		List<Account> list = accountMapper.findAllList(new Account());
		if (list.size()>0){
			for (Account account : list) {
				BigDecimal dynamicProfit = BigDecimal.valueOf(account.getDynamicProfit());
				//总动态收益到达5000并高于5000
				if (dynamicProfit.compareTo(BigDecimal.valueOf(5000)) == 0 || dynamicProfit.compareTo(BigDecimal.valueOf(5000)) == 1){
					//查询该用户持有的上架中的订单
					Orders orders = new Orders();
					orders.setMember(account.getMember());
					orders.setOrdersStatus("0");
					List<Orders> ordersList = ordersMapper.findList(orders);
					if (ordersList.size()>0){
						for (Orders orders1 : ordersList) {
							//查询出售订单商品
							Goods goods = goodsMapper.get(orders1.getGoods().getId());
							if (goods != null){
								//价格低于500，跳到下一个循环
								BigDecimal money = BigDecimal.valueOf(goods.getPrice());
								if (money.compareTo(BigDecimal.valueOf(500)) == -1){
									continue;
								//价格不低于500的删除此订单及商品   （逻辑删除）
								}else {
									//如果订单价格高于500，多出的钱返还到用户钱包余额
									if (money.compareTo(BigDecimal.valueOf(500)) == 1){
										BigDecimal m = BigDecimal.valueOf(account.getYue());
										BigDecimal balance = BigDecimal.valueOf(account.getYue()).add(money).subtract(BigDecimal.valueOf(500));
										account.setYue(balance.doubleValue());
										account.preUpdate();
										accountMapper.update(account);
										//插入订单返还余额明细
										OrderBalance orderBalance = new OrderBalance();
										orderBalance.setId(IdGen.uuid());
										orderBalance.setUpBalance(m.doubleValue());
										orderBalance.setMember(account.getMember());
										orderBalance.setOrderNo(orders1.getOrdersNo());
										orderBalance.setBackBalance(money.subtract(BigDecimal.valueOf(500)).doubleValue());
										orderBalance.setMoney(goods.getPrice());
										orderBalance.setBalanceFlag("2");
										orderBalance.setIsNewRecord(true);
										orderBalance.preInsert();
										orderBalanceMapper.insert(orderBalance);
									}
									ordersMapper.deleteByLogic(orders1);
									//关联商品删除
									goodsMapper.deleteByLogic(goods);
									break;
								}
							}
						}
					}
				}
			}
		}
	}

	/**
	 * 每天01:30 按设置百分比释放冻结金额
	 */
	@Transactional(readOnly = false)
	public void releaseFrozenMoney() {
		//查询所有账户钱包
		List<Account> accountList = accountMapper.findAllList(new Account());
		if (accountList.size()>0){
			for (Account account : accountList) {
				if (account.getFrozenMoney() != null && account.getReleasePercentage() != null){
					BigDecimal m = BigDecimal.valueOf(account.getFrozenMoney());
					BigDecimal mm = BigDecimal.valueOf(account.getYue());
					//如果冻结金额大于0
					if (BigDecimal.valueOf(account.getFrozenMoney()).compareTo(BigDecimal.valueOf(0)) == 1
							&& BigDecimal.valueOf(account.getReleasePercentage()).compareTo(BigDecimal.valueOf(0)) == 1){
						//换算释放百分比
						BigDecimal percentage = BigDecimal.valueOf(account.getReleasePercentage())
								.divide(BigDecimal.valueOf(100),3, RoundingMode.HALF_DOWN);
						//释放金额
						BigDecimal releaseMoney = BigDecimal.valueOf(account.getFrozenMoney()).multiply(percentage);
						//更新账户钱包
						account.setYue(BigDecimal.valueOf(account.getYue()).add(releaseMoney).doubleValue());
						account.setFrozenMoney(BigDecimal.valueOf(account.getFrozenMoney()).subtract(releaseMoney).doubleValue());
						account.preUpdate();
						accountMapper.update(account);
						//记录明细
						OrderBalance orderBalance = new OrderBalance();
						orderBalance.setId(IdGen.uuid());
						orderBalance.setUpBalance(mm.doubleValue());
						orderBalance.setMember(account.getMember());
						orderBalance.setMoney(m.doubleValue());
						orderBalance.setBackBalance(releaseMoney.doubleValue());
						orderBalance.setBalanceFlag("4");
						orderBalance.setIsNewRecord(true);
						orderBalance.preInsert();
						orderBalanceMapper.insert(orderBalance);
					}
				}
			}
		}
	}


	/**
	 * 10:40 1区未使用的预约费返还
	 */
	@Transactional(readOnly = false)
	public void returnYuyueBalance() {
		//查询未出局的预约
		Yuyue yuyue = new Yuyue();
		yuyue.setZone("0");
		yuyue.setIsOver("0");
		List<Yuyue> yuyueList = yuyueMapper.findList(yuyue);
		for (Yuyue yuyue1 : yuyueList) {
			//账户钱包    返还预约手续费
			Account account = new Account();
			account.setMember(yuyue1.getMember());
			List<Account> accountList = accountMapper.findList(account);
			if (accountList.size()>0){
				accountList.get(0).setYue(accountList.get(0).getYue()+yuyue1.getMoney());
				accountList.get(0).preUpdate();
				accountMapper.update(accountList.get(0));
				//预约出局
				yuyue1.setIsOver("1");
				yuyue1.setIsBack("1");
				yuyue1.setGiveMoney(yuyue1.getMoney());
				yuyue1.preUpdate();
				yuyueMapper.update(yuyue1);
			}
		}
	}



	/**
	 * 14:40 2区未使用的预约费返还
	 */
	@Transactional(readOnly = false)
	public void returnYuyueBalance1() {
		//查询未出局的预约
		Yuyue yuyue = new Yuyue();
		yuyue.setZone("1");
		yuyue.setIsOver("0");
		List<Yuyue> yuyueList = yuyueMapper.findList(yuyue);
		for (Yuyue yuyue1 : yuyueList) {
			//账户钱包    返还预约手续费
			Account account = new Account();
			account.setMember(yuyue1.getMember());
			List<Account> accountList = accountMapper.findList(account);
			if (accountList.size()>0){
				accountList.get(0).setYue(accountList.get(0).getYue()+yuyue1.getMoney());
				accountList.get(0).preUpdate();
				accountMapper.update(accountList.get(0));
				//预约出局
				yuyue1.setIsOver("1");
				yuyue1.setIsBack("1");
				yuyue1.setGiveMoney(yuyue1.getMoney());
				yuyue1.preUpdate();
				yuyueMapper.update(yuyue1);
			}
		}
	}


	/**
	 * 每天记录发放奖励等
	 */
	@Transactional(readOnly = false)
	public void record() {
		Double todayBuy = 0.0;             //每日销售额
		Integer todayNum = 0;          //每日增长人数
		Double todayDynamic = 0.0;         //每日动态
		Double todayCost = 0.0;            //每日手续费

		todayNum = memberService.getTodayNum();
		if(todayNum == null) {
			todayNum = 0;
		}
		todayDynamic = dynamicRecordService.getTodayDynamic();
		if(todayDynamic == null){
			todayDynamic =0.0;
		}


		todayCost = teamServiceService.getTodayStatic();
		if(todayCost == null){
			todayCost =0.0;
		}

		List<Orders> listOrders = ordersService.findTodayList(new Orders());
		if(listOrders.size()>0) {
			for(int i = 0;i<listOrders.size();i++) {
				todayBuy += listOrders.get(i).getMoney() == null?0:listOrders.get(i).getMoney();
			}
		}
		Record record=new Record();
		record.setDynamic(todayDynamic);
		record.setNum(todayNum);
		record.setSale(todayBuy);
		record.setService(todayCost);
	}


	/**
	 * 19:40 3区未使用的预约费返还
	 */
	@Transactional(readOnly = false)
	public void returnYuyueBalance2() {
		//查询未出局的预约
		Yuyue yuyue = new Yuyue();
		yuyue.setZone("2");
		yuyue.setIsOver("0");
		List<Yuyue> yuyueList = yuyueMapper.findList(yuyue);
		for (Yuyue yuyue1 : yuyueList) {
			//账户钱包    返还预约手续费
			Account account = new Account();
			account.setMember(yuyue1.getMember());
			List<Account> accountList = accountMapper.findList(account);
			if (accountList.size()>0){
				accountList.get(0).setYue(accountList.get(0).getYue()+yuyue1.getMoney());
				accountList.get(0).preUpdate();
				accountMapper.update(accountList.get(0));
				//预约出局
				yuyue1.setIsOver("1");
				yuyue1.setIsBack("1");
				yuyue1.setGiveMoney(yuyue1.getMoney());
				yuyue1.preUpdate();
				yuyueMapper.update(yuyue1);
			}
		}
	}


	/**
	 * 重置用户分区能量值   10
	 */
	@Transactional(readOnly = false)
	public void resetEnergyValue() {
		List<PartitionInfo> list = partitionInfoMapper.findAllList(new PartitionInfo());
		if (list.size()>0){
			for (PartitionInfo partitionInfo : list) {
				partitionInfo.setEnergyValue(10);
				partitionInfo.preUpdate();
				partitionInfoMapper.update(partitionInfo);
			}
		}
	}


	/**
	 * 结束拼团
	 */
	@Transactional(readOnly = false)
	public void endTheGroup() {
		//未结束的拼团
		GroupRecord entity = new GroupRecord();
		entity.setIsEnd("0");
		List<GroupRecord> list = groupRecordMapper.findList(entity);
		if (list.size()>0){
			for (GroupRecord groupRecord : list) {
				if ("0".equals(groupRecord.getGroupStatus())){
					//未成团的========================================================
					groupRecord.setIsEnd("1");
					groupRecord.preUpdate();
					groupRecordMapper.update(groupRecord);
					GroupOrders groupOrders = new GroupOrders();
					groupOrders.setGroupRecord(groupRecord);
					List<GroupOrders> ordersList = groupOrdersMapper.findList(groupOrders);
					if (ordersList.size()>0){
						for (GroupOrders orders : ordersList) {
							orders.setOrderStatus("2");
							orders.preUpdate();
							groupOrdersMapper.update(orders);
							Member member = memberService.get(orders.getMember().getId());
							Account account = accountMapper.get(member.getAccount().getId());
							account.setYue(account.getYue()+orders.getMoney());
							account.preUpdate();
							accountMapper.update(account);
							GroupReturn groupReturn = new GroupReturn();
							groupReturn.setId(IdGen.uuid());
							groupReturn.setMember(member);
							groupReturn.setMoney(orders.getMoney());
							groupReturn.setOrderNo(orders.getOrderNo());
							groupReturn.setSessions(groupRecord.getSessions());
							groupReturn.setIsNewRecord(true);
							groupReturn.preInsert();
							groupReturnMapper.insert(groupReturn);
						}
					}
				}
			}
		}
	}


	/**
	 * 发放极差
	 */
	@Transactional(readOnly = false)
	public void grantRecord() {
		String name = "";
		Double m = 0.00;
		List<Member> list = memberService.findAllList(new Member());
		if (list.size()>0){
			for (Member member : list) {
				if (member.getP() != null){
					Member upMember = memberService.get(member.getP().getId());
					while (upMember != null){
						if (upMember.getNum()>=5 && !"admin".equals(upMember.getLoginName())){
							Account account = accountMapper.get(upMember.getAccount().getId());
							//代理奖发放
							if (account.getTeam()>0&&account.getTeam()<=200){
								name="团队奖1";
								m=account.getTeam()*0.5;
								account.setYue(account.getYue()+m);
								//dynamicProfit   总动态收益
								account.setDynamicProfit(account.getDynamicProfit()+m);
								//todayDynamic    今日动态收益
								account.setTodayDynamic(account.getTodayDynamic()+m);
								//totalProfit     总收益
								account.setTotalProfit(account.getTotalProfit()+m);
								//todayProfit     今日总收益
								account.setTodayProfit(account.getTodayProfit()+m);
								//TodayTeam     今日团队奖励
								account.setTodayTeam(m);
							}else if (account.getTeam()>200&&account.getTeam()<=2000){
								name="团队奖2";
								m=account.getTeam()*1;
								account.setYue(account.getYue()+m);
								//dynamicProfit   总动态收益
								account.setDynamicProfit(account.getDynamicProfit()+m);
								//todayDynamic    今日动态收益
								account.setTodayDynamic(account.getTodayDynamic()+m);
								//totalProfit     总收益
								account.setTotalProfit(account.getTotalProfit()+m);
								//todayProfit     今日总收益
								account.setTodayProfit(account.getTodayProfit()+m);
								//TodayTeam     今日团队奖励
								account.setTodayTeam(m);
							}else if (account.getTeam()>2000&&account.getTeam()<=20000){
								name="团队奖3";
								m=account.getTeam()*1.5;
								account.setYue(account.getYue()+m);
								//dynamicProfit   总动态收益
								account.setDynamicProfit(account.getDynamicProfit()+m);
								//todayDynamic    今日动态收益
								account.setTodayDynamic(account.getTodayDynamic()+m);
								//totalProfit     总收益
								account.setTotalProfit(account.getTotalProfit()+m);
								//todayProfit     今日总收益
								account.setTodayProfit(account.getTodayProfit()+m);
								//TodayTeam     今日团队奖励
								account.setTodayTeam(m);
							}else if (account.getTeam()>20000){
								name="团队奖4";
								m=account.getTeam()*2;
								account.setYue(account.getYue()+m);
								//dynamicProfit   总动态收益
								account.setDynamicProfit(account.getDynamicProfit()+m);
								//todayDynamic    今日动态收益
								account.setTodayDynamic(account.getTodayDynamic()+m);
								//totalProfit     总收益
								account.setTotalProfit(account.getTotalProfit()+m);
								//todayProfit     今日总收益
								account.setTodayProfit(account.getTodayProfit()+m);
								//TodayTeam     今日团队奖励
								account.setTodayTeam(m);
							}
							if (m>0){
								//插入收益记录
								DynamicRecord dynamicRecord = new DynamicRecord();
								dynamicRecord.setId(IdGen.uuid());
								dynamicRecord.setFrommem(upMember);
								dynamicRecord.setMember(upMember);
								dynamicRecord.setMoney(m);
								dynamicRecord.setName(name);
								dynamicRecord.setIsNewRecord(true);
								dynamicRecord.preInsert();
								dynamicRecordMapper.insert(dynamicRecord);
							}
							accountMapper.update(account);
							if (upMember.getP() != null){
								upMember = memberService.get(upMember.getP().getId());
							}else {
								break;
							}
						}

					}
				}
			}

		}

	}

	/**
	 * 每日23:55撤销所有买卖订单
	 */
	@Transactional(readOnly = false)
	public void cancelTrades() {
		// 撤销所有相关商品的买卖订单
//		List<PurchaseOrder> purchaseOrders = purchaseOrderService.findList(new PurchaseOrder());
//		if (purchaseOrders.size()>0){
//			for (PurchaseOrder order : purchaseOrders) {
//				order.setIsRevoke("1");
				purchaseOrderService.revokeOrders();
//			}
//		}
//		SaleOrder saleOrder = new SaleOrder();
//		saleOrder.setIsRevoke("0");
//		List<SaleOrder> saleOrders = saleOrderService.findListAll(saleOrder);
//		if (saleOrders.size()>0){
//			for (SaleOrder order : saleOrders) {
//				order.setIsRevoke("1");
				saleOrderService.revokeOrders();
//				saleOrderService.save(order);
				//每单手续费
//				double c = BigDecimal.valueOf(order.getCharge()).divide(BigDecimal.valueOf(order.getNum()),2,BigDecimal.ROUND_HALF_DOWN).doubleValue();
//				//剩余手续费返还
//				double charge = c * order.getNonNum();
//				Member m = memberService.get(order.getMember().getId());
//				if (m != null){
//					Account account = accountMapper.get(m.getAccount().getId());
//					if (account != null){
//						account.setYue(account.getYue() + charge);
//						account.preUpdate();
//						accountMapper.update(account);
//					}
//				}
//			}
//		}
	}

	/**
	 * 每日00:15查询认购开始的物品并复投
	 */
	@Transactional(readOnly = false)
	public void reInvestment() {
		try {
			subGoodsService.startSubscription();
		}catch (Exception e){
			e.printStackTrace();
			//手动回滚
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}

	}

	/**
	 * 记录每日交易线数据
	 */
	@Transactional(readOnly = false)
	public void recordTrading() {
		SubGoods subGoods = new SubGoods();
		subGoods.setIsUnloading("0");
		List<SubGoods> goodsList = subGoodsService.findList(subGoods);
		if (goodsList.size()>0){
			for (SubGoods goods : goodsList) {
				TradeRecord tradeRecord = new TradeRecord();
				tradeRecord.setSubGoods(goods);
				List<TradeRecord> todayInfo = tradeRecordService.findSameDayList(tradeRecord);
				if (todayInfo.size()>0){
					TradingLine tradingLine = new TradingLine();
					tradingLine.setSubGoods(goods);
					tradingLine.setStartPrice(todayInfo.get(todayInfo.size()-1).getPrice());
					tradingLine.setEndPrice(todayInfo.get(0).getPrice());
					Optional<TradeRecord> maxTrade = todayInfo.stream().max(Comparator.comparingDouble(TradeRecord::getPrice));
					Optional<TradeRecord> minTrade = todayInfo.stream().min(Comparator.comparingDouble(TradeRecord::getPrice));
					tradingLine.setMaxPrice(maxTrade.get().getPrice());
					tradingLine.setMinPrice(minTrade.get().getPrice());
					tradingLine.setFlag("2");
					tradingLineService.save(tradingLine);
				}
			}
		}
	}


	/**
	 * 处理用户等级
	 */
	@Transactional(readOnly = false)
	public void correctMemberType() {
		memberService.manageMemberType();
	}


	/**
	 * 记录每时交易线数据
	 */
	@Transactional(readOnly = false)
	public void recordTrading1() {
		SubGoods subGoods = new SubGoods();
		subGoods.setIsUnloading("0");
		List<SubGoods> goodsList = subGoodsService.findList(subGoods);
		if (goodsList.size()>0){
			for (SubGoods goods : goodsList) {
				TradeRecord tradeRecord = new TradeRecord();
				tradeRecord.setSubGoods(goods);
				List<TradeRecord> todayInfo = tradeRecordService.findSameDayList(tradeRecord);
				if (todayInfo.size()>0){
					TradingLine tradingLine = new TradingLine();
					tradingLine.setSubGoods(goods);
					tradingLine.setStartPrice(todayInfo.get(todayInfo.size()-1).getPrice());
					tradingLine.setEndPrice(todayInfo.get(0).getPrice());
					Optional<TradeRecord> maxTrade = todayInfo.stream().max(Comparator.comparingDouble(TradeRecord::getPrice));
					Optional<TradeRecord> minTrade = todayInfo.stream().min(Comparator.comparingDouble(TradeRecord::getPrice));
					tradingLine.setMaxPrice(maxTrade.get().getPrice());
					tradingLine.setMinPrice(minTrade.get().getPrice());
					tradingLine.setFlag("1");
					tradingLineService.save(tradingLine);
				}
			}
		}
	}


	/**
	 * 记录每5分交易线数据
	 */
	@Transactional(readOnly = false)
	public void recordTrading2() {
		SubGoods subGoods = new SubGoods();
		subGoods.setIsUnloading("0");
		List<SubGoods> goodsList = subGoodsService.findList(subGoods);
		if (goodsList.size()>0){
			for (SubGoods goods : goodsList) {
				TradeRecord tradeRecord = new TradeRecord();
				tradeRecord.setSubGoods(goods);
				List<TradeRecord> todayInfo = tradeRecordService.findSameDayList(tradeRecord);
				if (todayInfo.size()>0){
					TradingLine tradingLine = new TradingLine();
					tradingLine.setSubGoods(goods);
					tradingLine.setStartPrice(todayInfo.get(todayInfo.size()-1).getPrice());
					tradingLine.setEndPrice(todayInfo.get(0).getPrice());
					Optional<TradeRecord> maxTrade = todayInfo.stream().max(Comparator.comparingDouble(TradeRecord::getPrice));
					Optional<TradeRecord> minTrade = todayInfo.stream().min(Comparator.comparingDouble(TradeRecord::getPrice));
					tradingLine.setMaxPrice(maxTrade.get().getPrice());
					tradingLine.setMinPrice(minTrade.get().getPrice());
					tradingLine.setFlag("0");
					tradingLineService.save(tradingLine);
				}
			}
		}
	}

	@Transactional(readOnly = false)
	public void createAccount() {
		List<Member> listAll = memberService.findListAll(new Member());
		if (listAll.size()>0){
			for (Member member : listAll) {
				Account account = accountMapper.get(member.getAccount().getId());
				if (account == null){
					Account account1 = new Account();
					account1.setId(member.getAccount().getId());
					account1.setMember(member);
					account1.setYue(0.0);
					account1.setBuy(0.0);
					account1.setTeam(0.0);
					account1.setValid(0.0);
					account1.setNum(0);
					account1.setTixian(0.0);
					account1.setDynamicProfit(0.0);
					account1.setTodayDynamic(0.0);
					account1.setTeamProfit(0.0);
					account1.setTodayTeam(0.0);
					account1.setTotalProfit(0.0);
					account1.setTodayProfit(0.0);
					account1.setIntegral(0.0);
					account1.setTeamService(0.0);
					account1.setExchangeCoupon(0.0);
					account1.setCreateDate(new Date());
					account1.setUpdateDate(new Date());
					accountMapper.insert(account1);
				}
			}
		}
	}


	@Transactional(readOnly = false)
	public void correctProfit() {
//		List<Member> listAll = memberService.findListAll(new Member());
//		if (listAll.size()>0){
//			Double teamSumSubPro = 0.0;
//			Double teamSumSub = 0.0;
//			for (Member member2 : listAll) {
//				Account account = accountMapper.get(member2.getAccount().getId());
//				if (account != null){
//					Member member3 = new Member();
//					member3.setP(member2);
//					List<Member> memberList = memberService.findListAll(member3);
//					//查询团队下级人员
//					List<Member>  queryList = new ArrayList<>();
//					List<Member> list = new ArrayList<>();
//					queryList.addAll(memberList);
//					list.addAll(memberList);
//					while (list.size()>0){
//						list.clear();
//						List<Member> list1 = new ArrayList<>();
//						for (Member member4 : queryList) {
//							Member entity = new Member();
//							entity.setP(member4);
//							List<Member> memberList1 = memberService.findListAll(entity);
//							memberList.addAll(memberList1);
//							list1.addAll(memberList1);
//						}
//						list.addAll(list1);
//						queryList.clear();
//						queryList.addAll(list1);
//					}
//					if (memberList.size()>0){
//						for (Member mem : memberList) {
//							SubRecord subRecord = new SubRecord();
//							subRecord.setMember(mem);
//							List<SubRecord> subRecords = subRecordMapper.findList(subRecord);
//							if (subRecords.size()>0){
//								teamSumSub += subRecords.stream().mapToDouble(SubRecord::getTotalPrice).sum();
//							}
//						}
//					}
//					Double d = 0.0;
//					DynamicRecord dynamicRecord = new DynamicRecord();
//					dynamicRecord.setMember(member2);
//					List<DynamicRecord> list1 = dynamicRecordMapper.findList(dynamicRecord);
//					if(list1.size()>0){
//						d += list1.stream().mapToDouble(DynamicRecord::getMoney).sum();
//					}
//					TeamService teamService = new TeamService();
//					teamService.setMember(member2);
//					List<TeamService> list2 = teamServiceMapper.findList(teamService);
//					if(list2.size()>0){
//						d += list2.stream().mapToDouble(TeamService::getMoney).sum();
//					}
//					TeamRecord teamRecord = new TeamRecord();
//					teamRecord.setMember(member2);
//					List<TeamRecord> list3 = teamRecordMapper.findList(teamRecord);
//					if(list3.size()>0){
//						d += list3.stream().mapToDouble(TeamRecord::getMoney).sum();
//					}
//					member2.setTeamSumSub(teamSumSub);
//					member2.setTeamSumSubPro(teamSumSubPro);
//					account.setTeam(teamSumSub);
//					account.setTeamProfit(d);
//					account.setTotalProfit(account.getDynamicProfit()+account.getTeamProfit());
//					accountMapper.update(account);
//					teamSumSub = 0.0;
//					teamSumSubPro = 0.0;
//
//				}
//
//			}
//		}

		List<Member> listAll = memberService.findListAll(new Member());
		if (listAll.size()>0){
			Double teamSumSubPro = 0.0;
			Double teamSumSub = 0.0;
			for (Member member2 : listAll) {
				Account account = accountMapper.get(member2.getAccount().getId());
				if (account != null){
					Member member3 = new Member();
					member3.setP(member2);
					List<Member> memberList = memberService.findListAll(member3);
					//查询团队下级人员
					List<Member>  queryList = new ArrayList<>();
					List<Member> list = new ArrayList<>();
					queryList.addAll(memberList);
					list.addAll(memberList);
					while (list.size()>0){
						list.clear();
						List<Member> list1 = new ArrayList<>();
						for (Member member4 : queryList) {
							Member entity = new Member();
							entity.setP(member4);
							List<Member> memberList1 = memberService.findListAll(entity);
							memberList.addAll(memberList1);
							list1.addAll(memberList1);
						}
						list.addAll(list1);
						queryList.clear();
						queryList.addAll(list1);
					}
					if (memberList.size()>0){
						for (Member mem : memberList) {
							SubRecord subRecord = new SubRecord();
							subRecord.setMember(mem);
							List<SubRecord> subRecords = subRecordMapper.findList(subRecord);
							if (subRecords.size()>0){
								teamSumSub += subRecords.stream().mapToDouble(SubRecord::getTotalPrice).sum();
							}

							TradeRecord tradeRecord = new TradeRecord();
							tradeRecord.setPurchaseMember(mem);
							List<TradeRecord> tradeRecordList = tradeRecordMapper.findList(tradeRecord);

							if (tradeRecordList.size()>0){
								teamSumSub += tradeRecordList.stream().mapToDouble(TradeRecord::getTotalPrice).sum();
							}
						}
					}
					account.setTeam(teamSumSub);
					accountMapper.update(account);
					teamSumSub = 0.0;
					teamSumSubPro = 0.0;

				}

			}
		}
	}

	@Transactional(readOnly = false)
	public void sendAllPrize() {
		try {
			List<PositionAssets> list = positionAssetsMapper.findList(new PositionAssets());
			if (list.size()>0){
				for (PositionAssets positionAssets : list) {
					if (positionAssets.getGoodsNum() > 0){
						Member member = memberService.get(positionAssets.getMember().getId());
						if (member != null){
							String ordersNo = member.getLoginName();
							Double charge = positionAssets.getNowTotal() * 0.1;
							teamServiceService.manageTeamService(member,charge,ordersNo);
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}

	}


	@Transactional(readOnly = false)
	public void subtractTeam() {
//		SubGoods subGoods = new SubGoods();
//		subGoods.setId("e9f221da8f724534a9d273dac15c82bd");
//		SubRecord subRecord = new SubRecord();
//		subRecord.setSubGoods(subGoods);
//		List<SubRecord> list = subRecordMapper.findList(subRecord);
//		if (list.size() > 0){
//			for (SubRecord record : list) {
//				Double money = record.getTotalPrice();
//				Member member = memberService.get(record.getMember().getId());
//				if (member != null){
//					if (member.getP() != null) {
//						Member pMember = memberService.get(member.getP().getId());
//						while (pMember != null) {
//							Account account = accountMapper.get(pMember.getAccount().getId());
//							account.setTeam(account.getTeam() - money);
//							account.preUpdate();
//							accountMapper.update(account);
//							if (pMember.getP() != null){
//								pMember = memberService.get(pMember.getP().getId());
//							}else {
//								break;
//							}
//						}
//					}
//				}
//			}
//		}

		//矫正业绩
		List<Member> listAll = memberService.findListAll(new Member());
		if (listAll.size()>0) {
			Double teamSumSubPro = 0.0;
			Double teamSumSub = 0.0;
			for (Member member2 : listAll) {
				Account account = accountMapper.get(member2.getAccount().getId());
				if (account != null) {
					Member member3 = new Member();
					member3.setP(member2);
					List<Member> memberList = memberService.findListAll(member3);
					//查询团队下级人员
					List<Member> queryList = new ArrayList<>();
					List<Member> list = new ArrayList<>();
					queryList.addAll(memberList);
					list.addAll(memberList);
					while (list.size() > 0) {
						list.clear();
						List<Member> list1 = new ArrayList<>();
						for (Member member4 : queryList) {
							Member entity = new Member();
							entity.setP(member4);
							List<Member> memberList1 = memberService.findListAll(entity);
							memberList.addAll(memberList1);
							list1.addAll(memberList1);
						}
						list.addAll(list1);
						queryList.clear();
						queryList.addAll(list1);
					}
					if (memberList.size() > 0) {
						for (Member mem : memberList) {
							Tixian tixian = new Tixian();
							tixian.setShenhe("1");
							tixian.setMember(mem);
							List<Tixian> tixianList = tixianMapper.findList(tixian);
							teamSumSub += tixianList.stream().mapToDouble(Tixian::getMoney).sum();

							Recharge recharge = new Recharge();
							recharge.setMemberId(mem.getId());
							recharge.setRechargeStatus("1");
							List<Recharge> rechargeList = rechargeMapper.findList(recharge);
							teamSumSubPro += rechargeList.stream().mapToDouble(Recharge::getRechargeMoney).sum();
						}
					}
					if (teamSumSubPro - teamSumSub > 0){
						account.setTeam(teamSumSubPro - teamSumSub);
					}else {
						account.setTeam(0.0);
					}
					accountMapper.update(account);
					teamSumSub = 0.0;
					teamSumSubPro = 0.0;

				}

			}
		}

		//添加团队长
//		List<Member> memberList = memberService.findListAll(new Member());
//		if (memberList.size() > 0){
//			for (Member member : memberList) {
//				if (member.getP() != null){
//					Member pMember = memberService.get(member.getP().getId());
//					while (pMember != null){
//						if (!"7359709a335b4053b2b470f9c54764a7".equals(pMember.getId())){
//							if (pMember.getP() != null){
//								if ("7359709a335b4053b2b470f9c54764a7".equals(pMember.getP().getId())){
//									member.setTeamManager(pMember);
//									memberService.save(member);
//									break;
//								}else {
//									pMember = memberService.get(pMember.getP().getId());
//								}
//							}else {
//								member.setTeamManager(pMember);
//								memberService.save(member);
//								break;
//							}
//						}else {
//							break;
//						}
//					}
//				}
//
//			}
//		}
	}

	@Transactional(readOnly = false)
	public void updateMembersPassword() {
		List<Member> memberList = memberService.findListAll(new Member());
		if (memberList.size() > 0){
			for (Member member : memberList) {
				String pwd = member.getPassword();
				member.setPassword(entryptPassword(pwd));
				memberService.save(member);
			}
		}
	}
}
